package com.itheima.service.impl;

import com.alibaba.dubbo.config.annotation.Service;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.itheima.dao.RoleDao;
import com.itheima.entity.PageResult;
import com.itheima.entity.QueryPageBean;
import com.itheima.pojo.Role;
import com.itheima.service.RoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashMap;
import java.util.List;

@Service(interfaceClass = RoleService.class)
@Transactional
public class RoleServiceImpl implements RoleService {

    @Autowired
    private RoleDao roleDao;

    @Override
    public PageResult pageQuery(QueryPageBean queryPageBean) {
        Integer currentPage = queryPageBean.getCurrentPage();
        Integer pageSize = queryPageBean.getPageSize();
        String queryString = queryPageBean.getQueryString();
        PageHelper.startPage(currentPage, pageSize);
        Page<Role> page = roleDao.selectByCondition(queryString);
        long total = page.getTotal();
        List<Role> rows = page.getResult();
        return new PageResult(total, rows);
    }

    @Override
    public Role findById(Integer id) {
        return roleDao.findById(id);
    }

    @Override
    public List<Integer> findPermissionIdByRoleId(Integer id) {
        return roleDao.findPermissionIdByRoleId(id);
    }

    @Override
    public void edit(Role role, Integer[] permissionIds) {
        //1.需要先根据检查组id删除中间表的关联数据
        roleDao.deleteAssociation(role.getId());
        Integer roleId = role.getId();
        //调方法
        setRoleAndPermission(roleId,permissionIds);
        //3.再向检查组表插入数据
        roleDao.edit(role);
    }





    @Override
    public void delete(Integer id) {
        //调用checkGroupDao完成删除
        //1.先检查检查组表和检查项是否有关联
        Long count = roleDao.findCountByRoleId(id);
        if(count != 0 ) {//检查组表和检查项表有关联
            //2.再通过检查组id删除中间关联表
            roleDao.deleteAssociation(id);
            roleDao.deleteUserAndRole(id);
            //3.最后删除检查组表中的数据
            roleDao.delete(id);
        }else{
            roleDao.delete(id);
        }

    }
    private void setRoleAndPermission(Integer roleId, Integer[] permissionIds) {
        if(permissionIds != null && permissionIds.length > 0 ){
            for (Integer permissionId : permissionIds) {
                HashMap<String, Integer> map = new HashMap<>();
                map.put("role_id",roleId);
                map.put("permission_id",permissionId);
                roleDao.setRoleAndPermission(map);
            }
        }
    }
    @Override
    public void add(Role role, Integer[] permissionIds) {
        //调用完成添加
        roleDao.add(role);
        Integer roleId = role.getId();
        setRoleAndPermission(roleId,permissionIds);
    }






    @Override
    public List<Role> findAll() {
        return roleDao.findAll();
    }


}
